package com.orange.main;

import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.orange.conf.entity.ConfigEntity;
import com.orange.expireFile.entity.ExpireFile;
import com.orange.expireFile.format.ExpireFileFormat;
import com.orange.monitor.FileMonitor;
import com.orange.quartz.context.QuartzJobContext;
import com.orange.utils.FileUtils;
import com.orange.utils.ReadPropertiesUtils;

public class QuartzyMain {

	private static final Logger logger = Logger.getLogger(QuartzyMain.class);

	public static void main(String[] args) throws Exception {
		
		// 初始化
		init();
		
		// 加载过期文件配置文档
		String expireFileXML = System.getProperty("user.dir") + "/src/main/resources/conf/expireFileInfos.xml";
		Map<String, ExpireFile> expireFileMap = initExpireFileMap(expireFileXML);

		// 根据配置起定时调度任务
		QuartzJobContext.initScheduleJobMap(expireFileMap);
		QuartzJobContext.setAllJobs();

		// 监控过期配置文件
		FileMonitor.runMonitor();
	}

	/**
	 * @Description: 初始化相关配置 
	 */
	public static void init() {
		// 初始化日志目录
		FileUtils.existDir(System.getProperty("user.dir") + "/logs");

		// 加载log4j
		String log4jPath = System.getProperty("user.dir") + "/src/main/resources/conf/log4j.properties";
		initLog4j(log4jPath);

		// 加载hadoop相关配置文档
		String hadoopFilePath = System.getProperty("user.dir") + "/src/main/resources/conf/conf.properties";
		initHadoopConf(hadoopFilePath);
	}
	
	/**
	 * @Description: 初始化log4j
	 * @param log4jPath
	 */
	public static void initLog4j(String log4jPath) {
		if (FileUtils.existFile(log4jPath)) {
			PropertyConfigurator.configure(log4jPath);
		} else {
			System.out.println("the log configuration file [" + log4jPath + "] isn't exist");
			System.exit(1);
		}
	}

	/**
	 * @Description: 初始化hadoop配置
	 * @param hadoopFilePath
	 */
	public static void initHadoopConf(String hadoopFilePath) {
		if (FileUtils.existFile(hadoopFilePath)) {
			ConfigEntity.init(ReadPropertiesUtils.readPropertie(hadoopFilePath));
		} else {
			System.out.println("the hadoop configuration file [" + hadoopFilePath + "] isn't exist");
			System.exit(1);
		}
	}

	/**
	 * @Description: 初始化expireFileMap
	 * @param expireFileXML
	 * @return
	 * @throws Exception
	 */
	public static Map<String, ExpireFile> initExpireFileMap(String expireFileXML) throws Exception {
		Map<String, ExpireFile> expireFileMap = null;
		if (FileUtils.existFile(expireFileXML)) {
			expireFileMap = ExpireFileFormat.getExpireFileMapByXml(expireFileXML);
		} else {
			logger.info("the expireFile configuration file [" + expireFileXML + "] isn't exist");
			System.exit(1);
		}
		return expireFileMap;
	}

}
